<template>
  <div class="app-container calendar-list-container">
    <div class="apply-query">
      <el-row class="filter-query">
        <el-col><span>{{$t('expensesStatisticsManage.expensesStatistics.queryCondition')}}</span></el-col>
      </el-row>
      <el-form :inline="true" :model="listQuery" label-width="120px" style="padding: 0 20px;">
        <el-row style="padding-bottom: 10px">
          <el-col :span="4">
            <div class="w20">
              <div class="labelName">{{$t('expensesStatisticsManage.expensesStatistics.employUserId')}}</div>
              <el-autocomplete style="width: 100%" clearable v-model="listQuery.employUserName" :fetch-suggestions="getUserList" :placeholder="$t('expensesStatisticsManage.expensesStatistics.enterEmployUserId')"></el-autocomplete>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="w20">
              <div class="labelName">Category</div>
              <el-select clearable v-model="listQuery.bg" @change="changeBg" :placeholder="$t('placeholder.choose')">
                <el-option v-for="item in bgList" :key="item" :label="item" :value="item"></el-option>
              </el-select>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="w20">
              <div class="labelName">Account</div>
              <el-select clearable v-model="listQuery.bu" @change="changeBu" :placeholder="$t('placeholder.choose')">
                <el-option v-for="item in buList" :key="item" :label="item" :value="item"></el-option>
              </el-select>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="w20">
              <div class="labelName">{{$t('expensesStatisticsManage.expensesStatistics.timeCondition')}}</div>
              <el-date-picker style="width: 100%" format="yyyy-MM-dd" value-format="yyyy-MM-dd HH:mm:ss" v-model="listQuery.timeCondition" type="daterange" range-separator="-" :start-placeholder="$t('placeholder.startDate')" :end-placeholder="$t('placeholder.endDate')"></el-date-picker>
            </div>
          </el-col>
          <el-col :span="4" style="margin-top: 32px">
            <div class="yt-btn yt-btn-ys" @click="handleFilter">{{$t('button.search')}}</div>
            <div class="yt-btn btn" @click="reset">{{$t('button.reset')}}</div>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <div class="data-list">
      <div class="list-content">
        <span>{{$t('expensesStatisticsManage.expensesStatistics.listTitle')}}</span>
      </div>
      <div class="list-operation">
        <!--新增-->
        <el-button class="yt-btn-ys" type="primary" @click="remit">{{$t('button.export')}}</el-button>
      </div>

      <el-table :data="list" :empty-text="$t('placeholder.emptyText')" border class="yt-table" style="width: 100%;" show-summary :summary-method="getSummaries" max-height="600">
        <!--<el-table-column type="index" align="center" :label="$t('expensesStatisticsManage.expensesStatistics.serialNum')" min-width="60"/>-->
        <el-table-column align="center" label="Account" prop="bu" min-width="100"/>
        <el-table-column align="center" :label="$t('expensesStatisticsManage.expensesStatistics.employName')" prop="employName" min-width="100"/>
        <el-table-column align="center" :label="$t('expensesStatisticsManage.expensesStatistics.passportCost')" prop="passportCost" min-width="100">
          <template slot-scope="scope">
            <div v-format="'#,##0'">{{ scope.row.passportCost }}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" :label="$t('expensesStatisticsManage.expensesStatistics.vehiclesAirplaneCost')" prop="vehiclesAirplaneCost" min-width="100">
          <template slot-scope="scope">
            <div v-format="'#,##0'">{{ scope.row.vehiclesAirplaneCost }}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" :label="$t('expensesStatisticsManage.expensesStatistics.vehiclesTrainCost')" prop="vehiclesTrainCost" min-width="100">
          <template slot-scope="scope">
            <div v-format="'#,##0'">{{ scope.row.vehiclesTrainCost }}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" :label="$t('expensesStatisticsManage.expensesStatistics.vehiclesPassengerCost')" prop="vehiclesPassengerCost" min-width="100">
          <template slot-scope="scope">
            <div v-format="'#,##0'">{{ scope.row.vehiclesPassengerCost }}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" :label="$t('expensesStatisticsManage.expensesStatistics.vehiclesHighSpeedRailCost')" prop="vehiclesHighSpeedRailCost" min-width="100">
          <template slot-scope="scope">
            <div v-format="'#,##0'">{{ scope.row.vehiclesHighSpeedRailCost }}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" :label="$t('expensesStatisticsManage.expensesStatistics.vehiclesMetroCost')" prop="vehiclesMetroCost" min-width="100">
          <template slot-scope="scope">
            <div v-format="'#,##0'">{{ scope.row.vehiclesMetroCost }}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" :label="$t('expensesStatisticsManage.expensesStatistics.vehiclesTaxiCost')" prop="vehiclesTaxiCost" min-width="100">
          <template slot-scope="scope">
            <div v-format="'#,##0'">{{ scope.row.vehiclesTaxiCost }}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" :label="$t('expensesStatisticsManage.expensesStatistics.oilCost')" prop="oilCost" min-width="100">
          <template slot-scope="scope">
            <div v-format="'#,##0'">{{ scope.row.oilCost }}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" :label="$t('expensesStatisticsManage.expensesStatistics.highwayCost')" prop="highwayCost" min-width="100">
          <template slot-scope="scope">
            <div v-format="'#,##0'">{{ scope.row.highwayCost }}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" :label="$t('expensesStatisticsManage.expensesStatistics.parkingCost')" prop="parkingCost" min-width="100">
          <template slot-scope="scope">
            <div v-format="'#,##0'">{{ scope.row.parkingCost }}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" :label="$t('expensesStatisticsManage.expensesStatistics.accommodationCost')" prop="accommodationCost" min-width="100">
          <template slot-scope="scope">
            <div v-format="'#,##0'">{{ scope.row.accommodationCost }}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" :label="$t('expensesStatisticsManage.expensesStatistics.dailyCost')" prop="dailyCost" min-width="100">
          <template slot-scope="scope">
            <div v-format="'#,##0'">{{ scope.row.dailyCost }}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" :label="$t('expensesStatisticsManage.expensesStatistics.otherCost')" prop="otherCost" min-width="100">
          <template slot-scope="scope">
            <div v-format="'#,##0'">{{ scope.row.otherCost }}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" :label="$t('expensesStatisticsManage.expensesStatistics.total')" prop="total" min-width="100">
          <template slot-scope="scope">
            <div v-format="'#,##0'">{{ scope.row.total }}</div>
          </template>
        </el-table-column>
      </el-table>

      <!-- <div class="pagination-container">
        <el-pagination @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        background
        :current-page.sync="listQuery.page"
        :page-sizes="[10, 20, 30, 50, 100, 200]"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
        </el-pagination>
      </div> -->
    </div>
  </div>
</template>

<script>
  import { selectBu, selectBg, listbgAndbu } from '@/api/bu/index';
  import { getUserInfoByName } from '@/api/dict/dictValue/index';
  import { statisticsByDetails } from '@/api/pmoReport/expensesStatisticsManage';
  import YtGetTemplateSelect from '@/components/Yt-template/getTemplateSelect.vue';
  import formatter from '@/utils/formatter';
  import format from '@/utils/format/format.js';

  export default {
    name: 'expensesStatistics',
    components: {
      YtGetTemplateSelect,
      'dict-select': () => import('@/components/Dict/dictValueSelect')
    },
    data() {
      return {
        formatter,
        listAll: this.$store.getters.allDic,
        listMapAll: this.$store.getters.allMapDic,
        listQuery: {
          order: '', // 降序（desc）/升序（asc）
          orderBy: '', // 排序字段
          page: 1,
          limit: 10,
          employUserName: '',
          employUserId: '',
          bu: '',
          bg: '',
          formFillingStartTime: '',
          formFillingEndTime: '',
          timeCondition: []
        },

        total: 0,
        list: [],
        buList: [],
        bgList: []
      };
    },
    mounted() {
      this.getQuery()
      this.changeBg(this.listQuery.bg)
      this.changeBu(this.listQuery.bu)
      if (this.listQuery.timeCondition.length > 0 || this.listQuery.employUserName !== '' || this.listQuery.employUserId !== '' || this.listQuery.bu !== '' || this.listQuery.bg !== '') {
        this.getList()
      }
    },
    methods: {
      getQuery() {
        const expensesStatisticsListQuery = window.sessionStorage.getItem('expensesStatisticsListQuery');
        if (expensesStatisticsListQuery) {
          this.listQuery = JSON.parse(expensesStatisticsListQuery);
        }
      },
      getSummaries(param) {
        const { columns, data } = param;
        const sums = [];
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = this.$t('expensesStatisticsManage.expensesStatistics.sum');
            return;
          }
          const values = data.map(item => Number(item[column.property]));
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            sums[index] = format('#,##0', sums[index])[2];
          }
        });
        return sums;
      },
      getBu() {
        selectBu().then(res => {
          this.buList = res.data;
        });
      },
      getBg() {
        selectBg().then(res => {
          this.bgList = res.data;
        });
      },
      changeBu(val) {
        // 联动bg
        if (val === '') {
          this.getBg()
        } else {
          listbgAndbu({ bu: val, bg: '' }).then(res => {
            this.bgList = res.data;
          });
        }
      },
      changeBg(val) {
        // 联动bu
        if (val === '') {
          this.getBu()
        } else {
          listbgAndbu({ bu: '', bg: val }).then(res => {
            this.buList = res.data;
          });
        }
      },
      getUserList(queryString, cb) {
        // 获取员工编号
        getUserInfoByName({ username: queryString }).then(res => {
          this.userList = res.data.rows;
          for (let i = 0; i < this.userList.length; i++) {
            this.userList[i].value = this.userList[i].username;
          }
          cb(this.userList);
        });
      },
      reset() {
        this.listQuery = {
          order: '', // 降序（desc）/升序（asc）
          orderBy: '', // 排序字段
          page: 1,
          limit: 10,
          employUserName: '',
          employUserId: '',
          bu: '',
          bg: '',
          formFillingStartTime: '',
          formFillingEndTime: '',
          timeCondition: []
        };

        this.getList();
        this.getBu();
        this.getBg();
      },
      handleFilter() {
        this.getList();
      },
      handleSizeChange(val) {
        this.listQuery.limit = val;
        this.getList();
      },
      handleCurrentChange(val) {
        this.listQuery.page = val;
        this.getList();
      },
      remit() {
        if (this.list.length > 0) {
          const a = document.createElement('a');
          const href = '/api/admin/excel/exportDetailsCount?employUserName=' + this.listQuery.employUserName + '&bu=' + this.listQuery.bu + '&bg=' + this.listQuery.bg + '&formFillingStartTime=' + this.listQuery.formFillingStartTime + '&formFillingEndTime=' + this.listQuery.formFillingEndTime + '&userId=' + this.$store.getters.info.id;
          a.download = Date.now();
          a.href = href;
          a.click();
        } else {
          this.$message.error(this.$t('expensesStatisticsManage.expensesStatistics.errorTip'));
        }
      },
      getList() {
        if (this.listQuery.timeCondition == null) {
          this.listQuery.formFillingStartTime = '';
          this.listQuery.formFillingEndTime = '';
        }
        if (this.listQuery.timeCondition && Array.isArray(this.listQuery.timeCondition) && this.listQuery.timeCondition.length === 2) {
          this.listQuery.formFillingStartTime = this.listQuery.timeCondition[0];
          this.listQuery.formFillingEndTime = this.listQuery.timeCondition[1];
        }
        console.log(this.listQuery, 'this.listQuery')
        statisticsByDetails(this.listQuery).then(res => {
          this.list = res.data.list
        });
      }
    },
    beforeDestroy() {
      window.sessionStorage.setItem('expensesStatisticsListQuery', JSON.stringify(this.listQuery))
    }
  };
</script>
<style scoped>
</style>
